<template>
	<view>
		<!-- #ifdef APP-PLUS -->
		<view id="canvas" class="canvas" :aaa="videoData" :change:aaa="canvas.create"></view>

		<!-- #endif -->
		<view class="flex">
			<view class="upload-box flex flex-x-y pr">
				<!-- 视频 -->
				<!-- <video style="width: 100%;height: 100%;border-radius: 20rpx;" :enable-play-gesture="true"
					:controls="false" :autoplay="false" :show-fullscreen-btn="false" :show-play-btn="false"
					v-if="videoLocal" :src="videoLocal" object-fit="cover" :show-center-play-btn="true"></video> -->
				<!-- 视频 -->
				<!-- 选择视频 -->
				<view v-if="videoLocal" style="width: 140rpx;height: 100%;">
					<image :src="videoFirstPic" mode="aspectFill" style="width: 100%;height: 100%;"></image>

					<!-- 播放图标 -->
					<view @tap.stop="look" style="position: absolute;width: 140rpx;height: 100%;top:0;left:0;"
						class="flex flex-x-y">
						<text class="iconfont icon-bofang color-ffffff fs-40" style="color: #FFFFFF;"></text>
					</view>
					<!-- 播放图标 -->
				</view>
				<view v-else class="zengjia-view flex flex-x-y" @tap.stop="choose_video">
					<view class="iconfont icon-zengjia"></view>
				</view>
				<!-- 选择视频 -->

				<!-- 进度 -->
				<view class="flex flex-x-b flex-y-center jindu-video-box" v-if="videoLocal && !value && process != -2">
					<view class="jindu">
						<view class="jindu-i" :style="{width: process + '%'}">
						</view>
					</view>
				</view>
				<!-- 进度 -->
				<!-- 删除 -->
				<!-- <view @tap.stop="clear_upload" class="video-delete-btn" style="color: red;"
					v-if="videoLocal && !disabled">
					<view class="iconfont icon-cuo" style="font-size: 30rpx;color: #FFFFFF;"></view>
				</view> -->
				<!-- 删除 -->


			</view>

		</view>
		<previewVideo ref="previewVideo"></previewVideo>
		<powers ref="powers"></powers>
	</view>
</template>

<script>
	export default {
		name: "upload-video",
		props: {
			value: {
				type: [String],
				default: '',
			},
			//视频分类
			videoType: {
				type: [Array],
				default: () => [],
			},
			disabled: {
				type: Boolean,
				default: false,
			}
		},
		data() {
			return {
				videoLocal: '', //本地视频地址
				upload_task: null, //上传任务
				sss: '',

				process: -2, // -1 上传失败 -2 不显示
				videoData: null,
				videoFirstPic: '', //视频首图
			};
		},
		created() {
			if (this.value) {
				this.videoLocal = this.value;
			}
		},
		methods: {
			choose_video() {
				if (this.disabled) return;

				this.$refs.powers.open({
					powersType: 'POWERS_IMAGE',
					success: () => {
						////////////

						let video_opts = {
							compressed: false,
							sourceType: ['album'],
						};
						this.chooseVideo(video_opts).then(res => {
							this.videoLocal = res.path;
							this.videoData = res;
							this.$emit('changeVideo', res);
							// #ifdef H5
							this.create(res);
							// #endif
							// #ifdef APP-PLUS

							// #endif
							// this.showToast('上传成功');
							this.start_upload();
							console.log('res', res);
						}).catch(() => {
							// this.showToast('上传失败');

						});
						////////////
					}
				});


			},
			upload_again() {

			},
			start_upload() {
				this.process = 0;
				this.$emit('input', '');
				if (this.upload_task) {
					this.upload_task.abort();
				}

				this.upload_task = uni.uploadFile({

					url: this.ROOT + '/upload/file',
					filePath: this.videoLocal,
					name: 'file',
					header: {
						token: uni.getStorageSync('ACCESS_TOKEN'),
					},
					success: img_data => {

						let data = JSON.parse(img_data.data);
						if (img_data.statusCode == 200 && img_data.errMsg == 'uploadFile:ok') {


							if (data.status == 200 && data.data) {
								this.$emit('input', data.data);
								this.process = 100;
							}

						} else {
							this.upload_fail();
						}
					},


				});
				this.upload_task.onProgressUpdate(res => {
					// console.log('onProgressUpdate', res);
					this.process = res.progress;
				});
			},
			upload_success() {

			},
			upload_fail() {
				this.$emit('input', '');
				this.process = -1;
				setTimeout(() => {
					this.videoLocal = '';
				}, 500);
			},
			clear_upload() {
				if (this.upload_task) {
					this.upload_task.abort();
				}
				this.$emit('input', '');
				this.process = -2;
				this.videoLocal = '';

			},
			look() {
				this.$refs.previewVideo.open({
					src: this.videoLocal,
				});
			},
			chooseVideo(opts) {
				const {
					camera,
					compressed,
					maxDuration,
					sourceType,
					extension
				} = opts;
				return new Promise((resolve, reject) => {
					uni.chooseVideo({
						camera,
						compressed,
						maxDuration,
						sourceType,
						extension,
						success(res) {
							const {
								tempFilePath,
								duration,
								size,
								height,
								width
							} = res;
							resolve({
								name: (res.tempFile && res.tempFile.name) || '',
								path: tempFilePath,
								size,
								type: (res.tempFile && res.tempFile.type) || '',
								width,
								height,
								duration,
								fileType: 'video',
								cloudPath: '',
							});
						},
						fail(res) {
							reject();
						},
					});
				});
			},
			change(e) {
				let arr = e.filter(val => val.is_selected);
				this.$emit('changType', arr[0].value);
			},
			getBase64(e) {
				this.videoFirstPic = e.base64;
			},
		}
	}
</script>

<script module="canvas" lang="renderjs">
	export default {
		mounted() {
			console.log('sssssssssssssssssssss');
		},
		methods: {
			// 视图层创建base64图片
			create(newValue, oldValue, ownerInstance) {

				console.log('render.js', newValue);
				// 第一次进入为空不操作
				if (newValue == null) {
					return
				}
				// 在缓存中创建video标签
				var video = document.createElement("VIDEO")
				// 通过setAttribute给video dom元素添加自动播放的属性，因为视频播放才能获取封面图    
				// 设置video自动播放属性
				video.autoplay = true
				// 该设置方法无效
				// video.setAttribute('autoplay', true)
				// 再添加一个静音的属性，否则自动播放会有声音
				// 该设置方法无效
				// video.setAttribute('muted', true)
				video.muted = true
				// 如果报错Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
				// 可以把下面两行代码加上，因为我用的线上video url，所以可能抛出了异常。大概意思就是跨域了toDataURL()使用了外域资源
				video.setAttribute('crossOrigin', 'anonymous')
				video.crossOrigin = '*'
				// 上面我们只是创建了video标签，视频播放需要内部的source的标签，scr为播放源
				video.innerHTML = '<source src=' + newValue.path + ' type="audio/mp4">'
				// 再创建canvas画布标签
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				// video注册canplay自动播放事件
				// 防止video不播放，所以手动加个播放操作
				video.play()
				// video播放事件
				video.addEventListener('canplay', () => {
					// 创建画布的宽高属性节点，就是图片的大小，单位PX
					var anw = document.createAttribute("width");
					anw.nodeValue = newValue.width;
					var anh = document.createAttribute("height");
					anh.nodeValue = newValue.height;
					canvas.setAttributeNode(anw);
					canvas.setAttributeNode(anh);
					// 画布渲染
					ctx.drawImage(video, 0, 0, newValue.width, newValue.height);
					// 生成base64图片，指定type为jpeg格式生成的图片base64编码会小很多
					var base64 = canvas.toDataURL('image/jpeg') // 这就是封面图片的base64编码
					// #ifdef H5

					this.videoFirstPic = base64;
					// #endif
					// 传递数据给逻辑层
					if (ownerInstance) {
						ownerInstance.callMethod('getBase64', {
							base64: base64
						})
					}

					// 删除创建的video 、canvas dom，要不然重新选取视频生成图片不生效
					// ps：开始有这个问题，但是后面不知道为什么又没有了，如果发现生成第一次base64之后再选择不生效，可以尝试一下把下方注释打开
					// document.body.removeChild(video)
					// document.body.removeChild(canvas)
				})
			}
		}
	}
</script>

<style lang="scss">
	.upload-box {
		width: 140rpx;
		height: 140rpx;
		border-radius: 20rpx;
		background-color: #F0F0F0;
		overflow: hidden;

		.iconfont {
			font-size: 46rpx;
			color: #D8D8D8;
		}

		.zengjia-view {
			width: 100%;
			height: 100%;
		}
	}

	.jindu {
		margin-top: 10rpx;
		width: 100%;
		background-color: #E9EBED;
		height: 8rpx;
		position: relative;
		border-radius: 4rpx;
		overflow: hidden;

		.jindu-i {
			height: 8rpx;
			background: $bgColor;
			position: absolute;
			border-radius: 4rpx;
			transition: width 0.2s;
		}
	}

	.jindu-video-box {
		position: absolute;
		bottom: 0;
		width: 100%;
		z-index: 10;
	}

	.video-delete-btn {
		position: absolute;
		right: 0;
		top: 0;
		width: 40rpx;
		height: 40rpx;
		// background-color: rgba(0, 0, 0, 0.3);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10;
	}
</style>
